<template>
  <div
    class="ai-dialog-overlay"
    @click="handleOverlayClick"
  >
    <div
      ref="dialogRef"
      class="ai-dialog"
      :class="{ 'dragging': isDragging, 'mobile': isMobile }"
      :style="dialogStyle"
      @click.stop
    >
      <!-- 对话框头部 -->
      <div class="dialog-header">
        <div
          class="header-left"
          @mousedown="startDrag"
          @touchstart="startDrag"
        >
          <div class="ai-avatar">
            <Icon
              name="robot"
              size="24"
            />
          </div>
          <div class="header-info">
            <h3 class="dialog-title">
              {{ currentFunctionConfig.title }}
            </h3>
            <p class="dialog-subtitle">
              {{ currentFunctionConfig.description }}
            </p>
          </div>
        </div>
        
        <div class="header-actions">
          <!-- 最小化按钮 -->
          <button 
            class="action-btn minimize-btn"
            :title="isMinimized ? '展开' : '最小化'"
            @click="toggleMinimize"
          >
            <Icon
              :name="isMinimized ? 'expand' : 'minimize'"
              size="16"
            />
          </button>
          
          <!-- 关闭按钮 -->
          <button
            class="action-btn close-btn"
            title="关闭"
            @click="$emit('close')"
          >
            <Icon
              name="close"
              size="16"
            />
          </button>
        </div>
      </div>

      <!-- 对话框内容 -->
      <div
        v-show="!isMinimized"
        class="dialog-content"
      >
        <!-- 功能选择标签页 -->
        <div class="function-tabs">
          <button
            v-for="(config, key) in aiStore.functionConfig"
            :key="key"
            class="function-tab"
            :class="{ active: aiStore.currentFunction === key }"
            @click="handleTabClick(key)"
          >
            <span class="tab-icon">
              <Icon
                :name="config.icon"
                size="16"
              />
            </span>
            <span class="tab-text">{{ config.title }}</span>
          </button>
        </div>

        <!-- 对话历史区域 -->
        <div
          ref="conversationArea"
          class="conversation-area"
        >
          <div
            v-if="filteredConversations.length === 0"
            class="empty-state"
          >
            <div class="empty-icon">
              <Icon
                :name="currentFunctionConfig.icon"
                size="48"
              />
            </div>
            <p class="empty-text">
              {{ currentFunctionConfig.description }}
            </p>
            <p
              v-if="!aiStore.hasConversations"
              class="empty-hint"
            >
              在下方输入框开始对话
            </p>
            <p
              v-else
              class="empty-hint"
            >
              暂无该功能的对话记录,开始新的对话吧
            </p>
          </div>
          
          <div
            v-else
            class="conversation-list"
          >
            <div
              v-for="conversation in filteredConversations"
              :key="conversation.id"
              class="conversation-item"
              :class="{ 'error': !conversation.success }"
            >
              <!-- 用户输入 -->
              <div class="message user-message">
                <div class="message-avatar user-avatar">
                  <Icon
                    name="user"
                    size="16"
                  />
                </div>
                <div class="message-content">
                  <div class="message-text">
                    {{ conversation.input }}
                  </div>
                  <div class="message-time">
                    {{ formatTime(conversation.timestamp) }}
                  </div>
                </div>
              </div>
              
              <!-- AI回答 -->
              <div class="message ai-message">
                <div class="message-avatar ai-avatar">
                  <Icon
                    name="ai"
                    size="16"
                  />
                </div>
                <div class="message-content">
                  <div
                    v-if="conversation.type !== 'scenario'"
                    class="message-text"
                  >
                    {{ conversation.output }}
                  </div>
                  <div
                    v-else
                    class="scenario-analysis"
                  >
                    <!-- 场景分析反馈 -->
                    <div
                      v-if="conversation.feedback && conversation.feedback.type === 'MORE_INFO_NEEDED'"
                      class="feedback-message"
                    >
                      <div class="feedback-header">
                        <Icon
                          name="info"
                          size="20"
                        />
                        <h4>需要更多信息</h4>
                      </div>
                      <p class="feedback-text">
                        {{ conversation.feedback.message }}
                      </p>
                      <div
                        v-if="conversation.feedback.suggestions && conversation.feedback.suggestions.length > 0"
                        class="feedback-suggestions"
                      >
                        <button 
                          v-for="(suggestion, index) in conversation.feedback.suggestions" 
                          :key="index"
                          class="suggestion-chip"
                          @click="applySuggestion(suggestion)"
                        >
                          {{ suggestion }}
                        </button>
                      </div>
                    </div>

                    <!-- 正常场景分析结果 -->
                    <div
                      v-else-if="conversation.analysis && conversation.success"
                      class="analysis-content"
                    >
                      <!-- 关键要点 -->
                      <div
                        v-if="getDisplayKeyPoints(conversation.analysis).length > 0"
                        class="analysis-section"
                      >
                        <div class="section-header">
                          <Icon
                            name="lightbulb"
                            size="16"
                          />
                          <h4>关键要点</h4>
                        </div>
                        <ul class="key-points-list">
                          <li
                            v-for="(point, index) in getDisplayKeyPoints(conversation.analysis)"
                            :key="index"
                            class="key-point-item"
                          >
                            <span class="point-number">{{ index + 1 }}</span>
                            <div
                              class="point-content"
                              v-html="formatCasePoint(point)"
                            />
                          </li>
                        </ul>
                      </div>
                      
                      <!-- 相关条文 -->
                      <div
                        v-if="getDisplayRelatedArticles(conversation.analysis).length > 0"
                        class="analysis-section"
                      >
                        <div class="section-header">
                          <Icon
                            name="book"
                            size="16"
                          />
                          <h4>相关条文</h4>
                        </div>
                        <div class="articles-list">
                          <div
                            v-for="(article, index) in getDisplayRelatedArticles(conversation.analysis)"
                            :key="index"
                            class="related-article-container"
                          >
                            <button
                              class="related-article-item"
                              @click="toggleArticleDetail(article)"
                            >
                              <Icon
                                name="forward"
                                size="12"
                              />
                              <span>{{ getArticleDisplayText(article) }}</span>
                              <Icon 
                                name="chevron-down" 
                                size="16" 
                                class="expand-icon" 
                                :class="{ 'expanded': expandedArticles[getArticleKey(article)] }"
                              />
                            </button>
                            <div
                              v-if="expandedArticles[getArticleKey(article)]"
                              class="article-detail-content"
                            >
                              <div
                                v-if="articleDetailsCache[getArticleKey(article)]"
                                class="detail-box"
                              >
                                <div class="detail-part">
                                  {{ articleDetailsCache[getArticleKey(article)].chapter_path }}
                                </div>
                                <p class="detail-text">
                                  {{ articleDetailsCache[getArticleKey(article)].content }}
                                </p>
                              </div>
                              <div
                                v-else
                                class="empty-detail"
                              >
                                <Icon
                                  name="info"
                                  size="16"
                                />
                                <span>暂无详细内容</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 初步建议 -->
                      <div
                        v-if="getDisplayPreliminaryAdvice(conversation.analysis)"
                        class="analysis-section"
                      >
                        <div class="section-header">
                          <Icon
                            name="info"
                            size="16"
                          />
                          <h4>初步建议</h4>
                        </div>
                        <div class="advice-content">
                          <p class="advice-text">
                            {{ getDisplayPreliminaryAdvice(conversation.analysis) }}
                          </p>
                        </div>
                      </div>

                      <!-- 风险提示 -->
                      <div
                        v-if="conversation.analysis.risks && conversation.analysis.risks.length > 0"
                        class="analysis-section"
                      >
                        <div class="section-header">
                          <Icon
                            name="warning"
                            size="16"
                          />
                          <h4>风险提示</h4>
                        </div>
                        <ul class="key-points-list">
                          <li
                            v-for="(risk, index) in conversation.analysis.risks"
                            :key="index"
                            class="key-point-item"
                          >
                            <span class="point-number">{{ index + 1 }}</span>
                            <span class="point-text">{{ risk }}</span>
                          </li>
                        </ul>
                      </div>

                      <!-- 解决方案建议 -->
                      <div
                        v-if="conversation.analysis.solutions && conversation.analysis.solutions.length > 0"
                        class="analysis-section"
                      >
                        <div class="section-header">
                          <Icon
                            name="check-circle"
                            size="16"
                          />
                          <h4>解决方案建议</h4>
                        </div>
                        <ul class="key-points-list">
                          <li
                            v-for="(solution, index) in conversation.analysis.solutions"
                            :key="index"
                            class="key-point-item"
                          >
                            <span class="point-number">{{ index + 1 }}</span>
                            <span class="point-text">{{ solution }}</span>
                          </li>
                        </ul>
                      </div>
                      
                      <!-- 空状态提示 -->
                      <div
                        v-if="getDisplayKeyPoints(conversation.analysis).length === 0 && getDisplayRelatedArticles(conversation.analysis).length === 0 && !getDisplayPreliminaryAdvice(conversation.analysis) && !conversation.analysis.risks?.length && !conversation.analysis.solutions?.length"
                        class="empty-analysis"
                      >
                        <Icon
                          name="warning"
                          size="24"
                        />
                        <p>AI未能生成有效的分析结果,请重新描述场景或稍后再试</p>
                      </div>
                    </div>
                    <!-- 错误消息 -->
                    <div
                      v-else
                      class="error-message"
                    >
                      <Icon
                        name="error"
                        size="20"
                      />
                      <span>{{ conversation.output }}</span>
                    </div>
                  </div>
                  <div class="message-actions">
                    <button
                      class="action-btn copy-btn"
                      title="复制"
                      @click="copyToClipboard(conversation.output)"
                    >
                      <Icon
                        name="copy"
                        size="12"
                      />
                    </button>
                  </div>
                  <div class="message-time">
                    {{ formatTime(conversation.timestamp) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-container">
            <textarea
              ref="inputRef"
              v-model="inputText"
              :placeholder="currentFunctionConfig.placeholder"
              class="input-field"
              :disabled="aiStore.isLoading"
              rows="1"
              @keydown="handleKeyDown"
              @input="handleInput"
              @click="handleInputClick"
              @focus="handleInputFocus"
            />
            
            <button
              class="send-btn"
              :disabled="!canSend"
              :title="aiStore.isLoading ? 'AI正在思考中...' : '发送'"
              @click="handleSendClick"
            >
              <Icon
                v-if="!aiStore.isLoading"
                name="send"
                size="20"
              />
              <div
                v-else
                class="loading-spinner"
              >
                <Icon
                  name="loading"
                  size="16"
                />
              </div>
            </button>
          </div>
          
          <!-- 快捷操作 - 已移除搜索建议板块 (v1.7.3) -->
          <!-- 搜索建议功能已隐藏，如需恢复请联系开发人员 -->
        </div>

        <!-- 底部操作栏 -->
        <div class="dialog-footer">
          <div class="footer-left">
            <button
              class="action-btn"
              title="清空历史"
              @click="clearHistory"
            >
              <Icon
                name="clear"
                size="16"
              />
            </button>
          </div>
          
          <div class="footer-right">
            <div
              class="ai-status"
              :class="statusClass"
            >
              <div class="status-dot" />
              <span class="status-text">{{ statusText }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useAIStore } from '@/stores/ai'
import articleService from '@/services/articleService'
import Icon from '@/components/common/Icon.vue'

const emit = defineEmits(['close'])
const aiStore = useAIStore()

// 响应式状态
const dialogRef = ref(null)
const conversationArea = ref(null)
const inputRef = ref(null)
const inputText = ref('')
const isDragging = ref(false)
const isMinimized = ref(false)
const dragOffset = ref({ x: 0, y: 0 })
const dialogPosition = ref({ x: 100, y: 100 })
const expandedArticles = ref({})
const articleDetailsCache = ref({})

// --- 数据兼容性辅助函数 ---
const getDisplayKeyPoints = (analysis) => {
  if (!analysis) return [];
  return analysis.key_points && analysis.key_points.length > 0 
    ? analysis.key_points 
    : analysis.legal_relations || [];
}

const getDisplayRelatedArticles = (analysis) => {
  if (!analysis) return [];
  const articles = analysis.related_articles && analysis.related_articles.length > 0
    ? analysis.related_articles
    : analysis.applicable_articles || [];
  
  // 调试日志：简要记录条文数据情况
  if (articles.length > 0) {
    const firstType = typeof articles[0];
    const hasContent = firstType === 'object' && articles[0].content;
    console.log(`✅ 相关条文数据: ${articles.length}条, 类型: ${firstType}, 有完整内容: ${hasContent}`);
  }
  
  return articles;
}

const getDisplayPreliminaryAdvice = (analysis) => {
  if (!analysis) return '';
  return analysis.preliminary_advice || analysis.rights_obligations || '';
}

// 获取文章的唯一标识（兼容字符串和对象格式）
const getArticleKey = (article) => {
  return typeof article === 'string' ? article : article.number;
}

// 获取文章的显示文本
const getArticleDisplayText = (article) => {
  if (typeof article === 'string') return article;
  return `${article.number} ${article.title || ''}`;
}

// 格式化案例要点，将"案例场景："和"解析："分别标记
const formatCasePoint = (point) => {
  if (!point) return '';
  
  // 匹配 "案例场景：...。解析：..." 格式
  const caseMatch = point.match(/^(.*?案例场景[：:]\s*)(.+?)(\s*[。.]\s*解析[：:]\s*)(.+)$/);
  
  if (caseMatch) {
    return `<div class="case-scenario"><strong>📋 案例场景：</strong>${caseMatch[2]}</div><div class="case-analysis"><strong>💡 解析：</strong>${caseMatch[4]}</div>`;
  }
  
  // 如果没有匹配到标准格式，尝试简单分割
  if (point.includes('案例场景：') || point.includes('解析：')) {
    return point
      .replace(/(案例场景[：:])/g, '<div class="case-scenario"><strong>📋 $1</strong>')
      .replace(/([。.])\s*(解析[：:])/g, '</div><div class="case-analysis"><strong>💡 $2</strong>')
      + '</div>';
  }
  
  // 如果格式不匹配，直接返回原文本
  return `<div class="point-text">${point}</div>`;
}
// ---

// 计算属性
const isMobile = computed(() => window.innerWidth <= 768)

const dialogStyle = computed(() => {
  if (isMobile.value) {
    return {
      position: 'fixed',
      top: '0',
      left: '0',
      right: '0',
      bottom: '0',
      transform: 'none'
    }
  }
  
  return {
    left: `${dialogPosition.value.x}px`,
    top: `${dialogPosition.value.y}px`
  }
})

const currentFunctionConfig = computed(() => 
  aiStore.functionConfig[aiStore.currentFunction] || aiStore.functionConfig.chat
)

const filteredConversations = computed(() => {
  console.log('Filtering conversations for function:', aiStore.currentFunction)
  console.log('Total conversations:', aiStore.conversations.length)
  
  const filtered = aiStore.conversations.filter(conv => {
    // chat功能显示所有对话
    if (aiStore.currentFunction === 'chat') {
      return true
    }
    // 其他功能只显示对应类型的对话
    return conv.type === aiStore.currentFunction
  })
  
  console.log('Filtered conversations:', filtered.length)
  return filtered
})

const canSend = computed(() => 
  inputText.value.trim().length > 0 && !aiStore.isLoading
)

const statusClass = computed(() => {
  if (aiStore.isLoading) return 'status-loading'
  if (aiStore.error) return 'status-error'
  if (aiStore.aiHealthStatus?.success) return 'status-healthy'
  return 'status-unknown'
})

const statusText = computed(() => {
  if (aiStore.isLoading) return 'AI思考中...'
  if (aiStore.error) return '服务异常'
  if (aiStore.aiHealthStatus?.success) return '服务正常'
  return '连接中...'
})

// 拖拽功能
const startDrag = (event) => {
  if (isMobile.value) return
  
  // 只在左键点击时开始拖拽
  if (event.type === 'mousedown' && event.button !== 0) return
  
  console.log('Start drag initiated')
  event.preventDefault()
  event.stopPropagation()
  
  const clientX = event.type === 'touchstart' ? event.touches[0].clientX : event.clientX
  const clientY = event.type === 'touchstart' ? event.touches[0].clientY : event.clientY
  
  // 添加延迟，避免与点击事件冲突
  setTimeout(() => {
    isDragging.value = true
    dragOffset.value = {
      x: clientX - dialogPosition.value.x,
      y: clientY - dialogPosition.value.y
    }
    
    if (event.type === 'touchstart') {
      document.addEventListener('touchmove', handleDrag, { passive: false })
      document.addEventListener('touchend', stopDrag)
    } else {
      document.addEventListener('mousemove', handleDrag)
      document.addEventListener('mouseup', stopDrag)
    }
  }, 100)
}

const handleDrag = (event) => {
  if (!isDragging.value || isMobile.value) return
  
  event.preventDefault()
  
  const clientX = event.type === 'touchmove' ? event.touches[0].clientX : event.clientX
  const clientY = event.type === 'touchmove' ? event.touches[0].clientY : event.clientY
  
  let newX = clientX - dragOffset.value.x
  let newY = clientY - dragOffset.value.y
  
  // 边界检测
  const dialogWidth = 400
  const dialogHeight = 600
  const maxX = window.innerWidth - dialogWidth
  const maxY = window.innerHeight - dialogHeight
  
  newX = Math.max(0, Math.min(newX, maxX))
  newY = Math.max(0, Math.min(newY, maxY))
  
  dialogPosition.value = { x: newX, y: newY }
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('touchmove', handleDrag)
  document.removeEventListener('touchend', stopDrag)
}

// 对话框交互
const handleOverlayClick = () => {
  if (!isMobile.value) return
  emit('close')
}

const toggleMinimize = () => {
  isMinimized.value = !isMinimized.value
}

// 标签页点击处理
const handleTabClick = (key) => {
  console.log('Tab clicked:', key, 'Current:', aiStore.currentFunction)
  aiStore.setCurrentFunction(key)
  console.log('Tab switched to:', aiStore.currentFunction)
}

// 输入框交互处理
const handleInputClick = (event) => {
  console.log('Input clicked')
  // 确保输入框获得焦点
  if (inputRef.value && !inputRef.value.disabled) {
    inputRef.value.focus()
  }
}

const handleInputFocus = (event) => {
  console.log('Input focused')
}

// 发送按钮点击处理
const handleSendClick = (event) => {
  console.log('Send button clicked')
  console.log('canSend:', canSend.value)
  console.log('inputText:', inputText.value)
  console.log('inputText.trim().length:', inputText.value.trim().length)
  console.log('aiStore.isLoading:', aiStore.isLoading)
  
  if (!canSend.value) {
    console.log('Send button disabled, cannot send')
    return
  }
  
  handleSend()
}

// 输入处理
const handleInput = () => {
  console.log('Input changed:', inputText.value)
  console.log('canSend updated:', canSend.value)
  
  // 自动调整textarea高度
  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.style.height = 'auto'
      inputRef.value.style.height = Math.min(inputRef.value.scrollHeight, 120) + 'px'
    }
  })
}

const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    handleSend()
  }
}

const handleSend = async () => {
  if (!canSend.value) return
  
  const text = inputText.value.trim()
  inputText.value = ''
  
  // 重置输入框高度
  if (inputRef.value) {
    inputRef.value.style.height = 'auto'
  }
  
  try {
    console.log('Sending message with function:', aiStore.currentFunction)
    
    switch (aiStore.currentFunction) {
      case 'explain':
        await aiStore.explainArticle(text)
        break
      case 'question':
        await aiStore.answerQuestion(text)
        break
      case 'scenario':
        await aiStore.analyzeScenario(text)
        break
      default:
        // 默认作为问答处理
        await aiStore.answerQuestion(text)
    }
    
    // 滚动到底部
    scrollToBottom()
  } catch (error) {
    console.error('AI调用失败:', error)
  }
}

// 获取建议类型
const getSuggestionType = (suggestion) => {
  if (typeof suggestion === 'object' && suggestion.type) {
    return suggestion.type
  }
  return 'default'
}

// 获取建议文本
const getSuggestionText = (suggestion) => {
  if (typeof suggestion === 'object' && suggestion.text) {
    return suggestion.text
  }
  return suggestion
}

// 获取建议描述
const getSuggestionDescription = (suggestion) => {
  if (typeof suggestion === 'object' && suggestion.description) {
    return suggestion.description
  }
  return ''
}

// 获取建议元数据
const getSuggestionMetadata = (suggestion) => {
  if (typeof suggestion === 'object' && suggestion.metadata) {
    return suggestion.metadata
  }
  return {
    related_articles_count: 0,
    applicable_scenarios: [],
    difficulty_level: 'medium'
  }
}

// 获取建议图标
const getSuggestionIcon = (suggestion) => {
  const type = getSuggestionType(suggestion)
  const iconMap = {
    'article': 'book-open',
    'question': 'question-mark-circle',
    'scenario': 'clipboard-document-list',
    'concept': 'light-bulb'
  }
  return iconMap[type] || 'magnifying-glass'
}

// 难度图标
const difficultyIcon = (level) => {
  const icons = {
    'easy': '🟢',
    'medium': '🟡',
    'hard': '🔴'
  }
  return icons[level] || '⚪'
}

// 难度文本
const difficultyText = (level) => {
  const texts = {
    'easy': '基础',
    'medium': '中等',
    'hard': '复杂'
  }
  return texts[level] || '未知'
}

// 处理建议点击（v1.7.2增强版 - 显示详细内容后自动执行）
const handleSuggestionClick = async (suggestion) => {
  try {
    console.log('🎯 [v1.7.2] 用户点击建议:', suggestion)
    
    // 兼容旧版字符串格式
    if (typeof suggestion === 'string') {
      console.log('  ℹ️ 旧版字符串格式，使用applySuggestion')
      applySuggestion(suggestion)
      return
    }
    
    // v1.7新版对象格式
    if (typeof suggestion === 'object') {
      const { type, action, target, text, description, metadata } = suggestion
      
      console.log(`  📦 建议类型: ${type}`)
      console.log(`  🎬 执行动作: ${action}`)
      console.log(`  🎯 目标内容: ${target}`)
      
      // 1. 确定目标功能
      const actionFunctionMap = {
        'explain': 'explain',
        'question': 'question',
        'scenario': 'scenario'
      }
      
      const targetFunction = actionFunctionMap[action] || 'question'
      
      console.log(`  🔄 切换功能: ${aiStore.currentFunction} → ${targetFunction}`)
      
      // 2. 切换功能标签
      aiStore.setCurrentFunction(targetFunction)
      
      // 3. 先在对话中插入建议详情（用户消息）
      const suggestionDetailMessage = formatSuggestionDetail(suggestion)
      aiStore.addMessage({
        role: 'user',
        content: suggestionDetailMessage,
        timestamp: new Date().toISOString()
      })
      
      console.log('  📄 已添加建议详情到对话')
      
      // 4. 填充输入内容
      inputText.value = target
      
      // 5. 等待下一帧，确保UI更新
      await nextTick()
      
      // 6. 自动执行查询
      console.log(`  🚀 自动执行查询: ${target}`)
      
      // 检查是否可以发送
      if (inputText.value.trim() && !aiStore.isLoading) {
        await handleSend()
        console.log('  ✅ 建议执行完成')
      } else {
        console.warn('  ⚠️ 无法执行：输入为空或正在加载中')
      }
    }
    
  } catch (error) {
    console.error('❌ 处理建议点击失败:', error)
    // 显示错误提示（如果有错误处理方法）
    if (aiStore.setError) {
      aiStore.setError('处理建议失败，请重试')
    }
  }
}

// 格式化建议详情为富文本
const formatSuggestionDetail = (suggestion) => {
  const { text, description, metadata, type } = suggestion
  
  // 类型标签映射
  const typeLabels = {
    'article': '📘 条文查询',
    'question': '❓ 法律问答',
    'scenario': '📋 场景分析',
    'concept': '💡 概念拓展'
  }
  
  // 难度标签
  const difficultyLabels = {
    'easy': '🟢 基础',
    'medium': '🟡 中等',
    'hard': '🔴 复杂'
  }
  
  let detail = `**${text}**\n\n`
  detail += `${typeLabels[type] || '🔍 查询'}\n\n`
  
  if (description) {
    detail += `📝 ${description}\n\n`
  }
  
  if (metadata) {
    if (metadata.related_articles_count) {
      detail += `📚 关联条文：${metadata.related_articles_count}条\n`
    }
    
    if (metadata.applicable_scenarios && metadata.applicable_scenarios.length > 0) {
      detail += `🏷️ 适用场景：${metadata.applicable_scenarios.join('、')}\n`
    }
    
    if (metadata.difficulty_level) {
      detail += `${difficultyLabels[metadata.difficulty_level] || '⚪ 未知'} 难度级别\n`
    }
  }
  
  return detail.trim()
}

const toggleArticleDetail = (article) => {
  // article可能是字符串（旧格式）或对象（新格式）
  const articleKey = typeof article === 'string' ? article : article.number;
  
  if (!articleKey) {
    console.warn('⚠️ articleKey为空，无法处理');
    return;
  }
  
  // 切换展开状态
  expandedArticles.value[articleKey] = !expandedArticles.value[articleKey];
  
  // 如果是对象格式（AI已返回完整内容），直接缓存
  if (typeof article === 'object') {
    if (article.content) {
      console.log(`✅ 缓存条文详情: ${articleKey}, 内容长度: ${article.content.length}字符`);
      articleDetailsCache.value[articleKey] = {
        content: article.content,
        part: '民法典',
        chapter_path: article.title || article.number
      };
    } else {
      console.warn(`⚠️ ${articleKey} 缺少content字段`);
    }
  }
}

const applySuggestion = (suggestion) => {
  inputText.value = suggestion
  handleInput()
}

const clearHistory = () => {
  if (confirm('确定要清空所有对话历史吗？')) {
    aiStore.clearConversations()
  }
}

const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    // 这里可以添加复制成功的提示
  } catch (error) {
    console.error('复制失败:', error)
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (conversationArea.value) {
      conversationArea.value.scrollTop = conversationArea.value.scrollHeight
    }
  })
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 监听对话变化，自动滚动到底部
watch(() => aiStore.conversations.length, () => {
  scrollToBottom()
})

// 监听对话框可见性，控制背景滚动
watch(() => aiStore.isDialogVisible, (isVisible) => {
  if (isVisible) {
    document.body.style.overflow = 'hidden';
  } else {
    document.body.style.overflow = '';
  }
}, { immediate: true }); // immediate确保初始状态正确

// 生命周期
onMounted(() => {
  // 初始化对话框位置
  if (!isMobile.value) {
    const centerX = (window.innerWidth - 400) / 2
    const centerY = (window.innerHeight - 600) / 2
    dialogPosition.value = { x: Math.max(50, centerX), y: Math.max(50, centerY) }
  }
  
  // 聚焦输入框
  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus()
    }
  })
})

onUnmounted(() => {
  stopDrag()
  
  // 确保组件卸载时恢复滚动
  document.body.style.overflow = ''
})
</script>

<style scoped>
.ai-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  z-index: 1001;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  overscroll-behavior: contain;
}

.ai-dialog {
  position: absolute;
  width: 400px;
  max-width: 90vw;
  height: 600px;
  max-height: 90vh;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overscroll-behavior: contain;
  pointer-events: auto;
}

.ai-dialog.mobile {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100% !important;
  height: 100% !important;
  max-width: none !important;
  max-height: none !important;
  border-radius: 0 !important;
  transform: none !important;
}

.ai-dialog.dragging {
  transform: scale(1.02);
  box-shadow: 0 25px 80px rgba(0, 0, 0, 0.4);
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  user-select: none;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
  cursor: move;
  padding: 4px;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.header-left:hover {
  background: rgba(255, 255, 255, 0.1);
}

.ai-avatar {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.header-info {
  min-width: 0;
  flex: 1;
}

.dialog-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  line-height: 1.2;
}

.dialog-subtitle {
  font-size: 12px;
  opacity: 0.8;
  margin: 2px 0 0 0;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.05);
}

.dialog-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
  position: relative;
}

.function-tabs {
  display: flex;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.function-tabs::-webkit-scrollbar {
  display: none;
}

.function-tab {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 12px 16px;
  border: none;
  background: none;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  flex-shrink: 0;
  font-size: 14px;
  position: relative;
  z-index: 10;
  pointer-events: auto;
}

.function-tab:hover {
  background: #e2e8f0;
  color: #475569;
}

.function-tab.active {
  background: white;
  color: #667eea;
  border-bottom: 2px solid #667eea;
}

.tab-icon {
  font-size: 16px;
}

.conversation-area {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 16px;
  background: #f8fafc;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
  touch-action: pan-y;
  overscroll-behavior: contain;
  position: relative;
  min-height: 0;
  max-height: 100%;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  color: #64748b;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 14px;
  opacity: 0.7;
}

.conversation-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.conversation-item {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-avatar {
  background: #3b82f6;
  color: white;
}

.ai-avatar {
  background: #667eea;
  color: white;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.user-message .message-content {
  background: #3b82f6;
  color: white;
  padding: 12px 16px;
  border-radius: 16px 16px 4px 16px;
}

.ai-message .message-content {
  background: white;
  border: 1px solid #e2e8f0;
  padding: 12px 16px;
  border-radius: 16px 16px 16px 4px;
}

.message-text {
  line-height: 1.5;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.scenario-analysis {
  line-height: 1.5;
}

.analysis-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.analysis-section {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  border-left: 3px solid #667eea;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.section-header h4 {
  font-size: 15px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.section-header .icon {
  color: #667eea;
}

/* 关键要点样式 */
.key-points-list {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.key-point-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  transition: all 0.2s;
}

.key-point-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  transform: translateY(-1px);
}

.point-number {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #667eea;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  font-weight: 600;
}

.point-text {
  flex: 1;
  color: #334155;
  line-height: 1.6;
  font-size: 14px;
}

.point-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.case-scenario {
  line-height: 1.8;
  color: #1e293b;
  padding: 12px;
  background: linear-gradient(135deg, #e0f2fe 0%, #dbeafe 100%);
  border-radius: 6px;
  border-left: 3px solid #3b82f6;
}

.case-scenario strong {
  color: #1e40af;
  display: block;
  margin-bottom: 6px;
}

.case-analysis {
  line-height: 1.8;
  color: #1e293b;
  padding: 12px;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-radius: 6px;
  border-left: 3px solid #f59e0b;
}

.case-analysis strong {
  color: #d97706;
  display: block;
  margin-bottom: 6px;
}

/* 反馈消息样式 */
.feedback-message {
  padding: 16px;
  background: #fffbeb;
  border: 1px solid #fde68a;
  border-radius: 8px;
  color: #b45309;
}

.feedback-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.feedback-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #92400e;
}

.feedback-text {
  margin: 0 0 16px 0;
  font-size: 14px;
  line-height: 1.6;
}

.feedback-suggestions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.suggestion-chip {
  padding: 6px 12px;
  background: #fef3c7;
  border: 1px solid #fde68a;
  border-radius: 16px;
  font-size: 13px;
  color: #92400e;
  cursor: pointer;
  transition: all 0.2s;
}

.suggestion-chip:hover {
  background: #fde68a;
  border-color: #facc15;
}

/* 相关条文样式 */
.articles-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.related-article-container {
  position: relative;
}

.related-article-item {
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
  font-size: 14px;
  line-height: 1.5;
  color: #475569;
  transition: all 0.2s;
  width: 100%;
  text-align: left;
}

.related-article-item:hover {
  border-color: #667eea;
  background: #f8fafc;
}

.related-article-item .icon {
  flex-shrink: 0;
  margin-top: 2px;
  color: #667eea;
}

.related-article-item span {
  flex: 1;
  text-align: left;
}

.expand-icon {
  transition: transform 0.3s ease;
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

.article-detail-content {
  padding: 12px;
  margin-top: 8px;
  background: #f8fafc;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.loading-detail, .error-detail, .empty-detail {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #64748b;
}

.error-detail {
  color: #ef4444;
}

.empty-detail {
  color: #94a3b8;
  font-size: 13px;
}

.detail-box .detail-part {
  font-size: 12px;
  color: #94a3b8;
  margin-bottom: 8px;
}

.detail-box .detail-text {
  font-size: 14px;
  line-height: 1.6;
  color: #334155;
  white-space: pre-wrap;
}


/* 初步建议样式 */
.advice-content {
  background: white;
  padding: 14px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.advice-text {
  margin: 0;
  color: #334155;
  line-height: 1.7;
  font-size: 14px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 空状态样式 */
.empty-analysis {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  color: #64748b;
  gap: 12px;
}

.empty-analysis .icon {
  color: #f59e0b;
}

.empty-analysis p {
  margin: 0;
  font-size: 14px;
}

/* 错误消息样式 */
.error-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 6px;
  color: #dc2626;
  font-size: 14px;
}

.error-message .icon {
  flex-shrink: 0;
}

.message-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.copy-btn {
  width: 24px;
  height: 24px;
  background: #f1f5f9;
  color: #64748b;
  border-radius: 4px;
}

.message-time {
  font-size: 12px;
  color: #94a3b8;
  margin-top: 4px;
}

.user-message .message-time {
  color: rgba(255, 255, 255, 0.7);
}

.input-area {
  border-top: 1px solid #e2e8f0;
  background: white;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  padding: 16px;
}

.input-field {
  flex: 1;
  min-height: 40px;
  max-height: 120px;
  padding: 10px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  resize: none;
  font-size: 14px;
  line-height: 1.4;
  outline: none;
  transition: border-color 0.2s;
  position: relative;
  z-index: 10;
  pointer-events: auto;
  cursor: text;
}

.input-field:focus {
  border-color: #667eea;
}

.input-field:disabled {
  background: #f8fafc;
  color: #94a3b8;
}

.send-btn {
  width: 40px;
  height: 40px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  flex-shrink: 0;
  position: relative;
  z-index: 10;
  pointer-events: auto;
}

.send-btn:hover:not(:disabled) {
  background: #5a67d8;
  transform: scale(1.05);
}

.send-btn:disabled {
  background: #cbd5e1;
  cursor: not-allowed;
  transform: none;
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.quick-actions {
  padding: 0 16px 16px;
  max-height: 400px;
  overflow-y: auto;
}

/* v1.7增强版建议卡片网格 */
.suggestions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
}

/* 建议卡片基础样式 */
.suggestion-card {
  padding: 12px;
  border-radius: 12px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.suggestion-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  font-size: 14px;
}

.card-icon {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.card-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-popularity {
  flex-shrink: 0;
  font-size: 12px;
  opacity: 0.8;
}

/* 卡片描述 */
.card-description {
  font-size: 12px;
  opacity: 0.7;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 卡片元数据 */
.card-metadata {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 4px;
}

.meta-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  background: rgba(0, 0, 0, 0.05);
  white-space: nowrap;
}

/* 难度标签 */
.difficulty-easy {
  background: rgba(34, 197, 94, 0.1);
  color: #16a34a;
}

.difficulty-medium {
  background: rgba(234, 179, 8, 0.1);
  color: #ca8a04;
}

.difficulty-hard {
  background: rgba(239, 68, 68, 0.1);
  color: #dc2626;
}

/* 7种类型的颜色主题 */
.suggestion-type-article {
  background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
  border-color: #93c5fd;
  color: #1e40af;
}

.suggestion-type-question {
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-color: #fcd34d;
  color: #92400e;
}

.suggestion-type-scenario {
  background: linear-gradient(135deg, #fce7f3 0%, #fbcfe8 100%);
  border-color: #f9a8d4;
  color: #831843;
}

.suggestion-type-concept {
  background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
  border-color: #6ee7b7;
  color: #065f46;
}


/* 响应式设计 */
@media (max-width: 768px) {
  .suggestions-grid {
    grid-template-columns: 1fr;
  }
  
  .card-title {
    font-size: 13px;
  }
  
  .card-description {
    font-size: 11px;
  }
}

/* 兼容旧版样式 */
.quick-suggestions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.suggestion-btn {
  padding: 6px 12px;
  background: #f1f5f9;
  color: #475569;
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  z-index: 10;
  pointer-events: auto;
}

.suggestion-btn:hover {
  background: #e2e8f0;
  border-color: #cbd5e1;
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

.footer-left {
  display: flex;
  gap: 8px;
}

.footer-right {
  display: flex;
  align-items: center;
}

.ai-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-healthy .status-dot {
  background: #10b981;
}

.status-error .status-dot {
  background: #ef4444;
}

.status-loading .status-dot {
  background: #f59e0b;
  animation: pulse 2s infinite;
}

.status-unknown .status-dot {
  background: #94a3b8;
}

.status-text {
  color: #64748b;
}

/* 错误状态样式 */
.conversation-item.error .ai-message .message-content {
  background: #fef2f2;
  border-color: #fecaca;
  color: #dc2626;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-dialog {
    border-radius: 0;
    overflow: hidden;
  }
  
  .dialog-header {
    padding: 12px 16px;
    flex-shrink: 0;
  }
  
  .dialog-title {
    font-size: 14px;
  }
  
  .dialog-subtitle {
    font-size: 11px;
  }
  
  .function-tabs {
    justify-content: space-around;
    padding: 0 8px;
    flex-shrink: 0;
  }
  
  .function-tab {
    padding: 10px 8px;
    font-size: 13px;
    flex: 1;
    justify-content: center;
    min-width: 0;
  }
  
  .tab-text {
    display: none;
  }
  
  .tab-icon {
    font-size: 18px;
  }
  
  .conversation-area {
    padding: 12px;
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }
  
  .input-container {
    padding: 12px;
  }
  
  .input-area {
    flex-shrink: 0;
  }
}

/* 滚动条样式 */
.conversation-area::-webkit-scrollbar {
  width: 4px;
}

.conversation-area::-webkit-scrollbar-track {
  background: transparent;
}

.conversation-area::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 2px;
}

.conversation-area::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>
